package com.ck.express.activity

import android.util.Log
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType.POSSIBLE_FORMATS
import com.google.zxing.DecodeHintType.TRY_HARDER
import com.google.zxing.MultiFormatReader
import com.google.zxing.NotFoundException
import com.google.zxing.PlanarYUVLuminanceSource
import com.google.zxing.common.HybridBinarizer


// 条码识别器 - BarcodeAnalyzer.kt
class BarcodeAnalyzer(private val listener: BarcodeListener) : ImageAnalysis.Analyzer {
    private val zxingScanner = MultiFormatReader().apply {
        val hints = mapOf(
            POSSIBLE_FORMATS to arrayListOf(
                BarcodeFormat.CODE_128,
                BarcodeFormat.CODE_39,
                BarcodeFormat.QR_CODE,
                BarcodeFormat.CODE_93,
                BarcodeFormat.EAN_13,
                BarcodeFormat.EAN_8,
                BarcodeFormat.UPC_A,
                BarcodeFormat.UPC_E,
                BarcodeFormat.DATA_MATRIX,
            ),
            TRY_HARDER to true
        )
        setHints(hints)
    }

    override fun analyze(image: ImageProxy) {
        val buffer = image.planes[0].buffer
        val imageData = ByteArray(buffer.remaining()).apply { buffer.get(this) }

        try {
            val source = PlanarYUVLuminanceSource(
                imageData,
                image.width,
                image.height,
                0, 0,
                image.width,
                image.height,
                false
            )

            val binaryBitmap = BinaryBitmap(HybridBinarizer(source))
            val result = zxingScanner.decodeWithState(binaryBitmap)

            listener.onBarcodeDetected(result.text)
        } catch (e: NotFoundException) {
            // 未识别到条码
        } catch (e: Exception) {
            Log.e("BarcodeAnalyzer", "条码解析错误", e)
        } finally {
            image.close()
        }
    }

    interface BarcodeListener {
        fun onBarcodeDetected(barcode: String)
    }
}